package com.example.supplychainbackend.service.Impl;

import com.example.supplychainbackend.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @Override
    public String storeFile(MultipartFile file) throws IOException {
        // 确保上传目录存在
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名（防止重名覆盖）
        String originalFileName = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFileName);
        String uniqueFileName = UUID.randomUUID() + fileExtension;

        // 存储文件
        Path filePath = uploadPath.resolve(uniqueFileName);
        Files.copy(file.getInputStream(), filePath);

        // 返回文件访问URL（根据实际部署环境调整）
        return "http://localhost:8080/api/files/" + uniqueFileName;
    }

    @Override
    public boolean deleteFileByUrl(String fileUrl) throws IOException {
        String fileName = extractFileNameFromUrl(fileUrl);
        return deleteFileByName(fileName);
    }

    @Override
    public Resource loadFileAsResource(String fileUrl) throws IOException {
        String fileName = extractFileNameFromUrl(fileUrl);
        Path filePath = getFilePath(fileName);

        try {
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() && resource.isReadable()) {
                return resource;
            } else {
                throw new IOException("文件不存在或不可读: " + fileName);
            }
        } catch (MalformedURLException e) {
            throw new IOException("文件路径格式错误: " + filePath, e);
        }
    }

    @Override
    public MediaType getMediaType(String fileUrl) {
        String fileName = extractFileNameFromUrl(fileUrl);
        String extension = getFileExtension(fileName);

        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return MediaType.IMAGE_JPEG;
            case "png":
                return MediaType.IMAGE_PNG;
            case "gif":
                return MediaType.IMAGE_GIF;
            case "pdf":
                return MediaType.APPLICATION_PDF;
            case "txt":
                return MediaType.TEXT_PLAIN;
            case "html":
                return MediaType.TEXT_HTML;
            case "json":
                return MediaType.APPLICATION_JSON;
            case "xml":
                return MediaType.APPLICATION_XML;
            default:
                return MediaType.APPLICATION_OCTET_STREAM;
        }
    }

    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public Path getFilePath(String fileName) {
        return Paths.get(uploadDir).resolve(fileName);
    }

    public String extractFileNameFromUrl(String fileUrl) {
        if (fileUrl == null || !fileUrl.startsWith("/files/")) {
            throw new IllegalArgumentException("无效的文件URL: " + fileUrl);
        }
        return fileUrl.substring("/files/".length());
    }

    public boolean deleteFileByName(String fileName) throws IOException {
        Path filePath = getFilePath(fileName);

        if (Files.exists(filePath)) {
            Files.delete(filePath);
            return true;
        }
        return false;
    }

    public boolean fileExists(String fileUrl) {
        try {
            String fileName = extractFileNameFromUrl(fileUrl);
            Path filePath = getFilePath(fileName);
            return Files.exists(filePath);
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
}
